﻿using System;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Windows.Forms;
using CommonLib;
using WordStat.Anylize;

namespace WordStat
{
    internal static class TextFileService
    {
        public static void AddFileToDb(string fileName)
        {
            var article = new WordStatArticle
                              {
                                  Author = string.Empty,
                                  Title = string.Empty,
                                  Date = DateTime.Now,
                                  Source = string.Empty,
                                  Url = Path.GetFileName(fileName),
                                  Text = GetText(fileName)
                              };

            article.Words = WordParser.GetWords(article.Text);

            var window = new Gui.AddNewArticleWindow();

            window.SetData(article);

            var dlgRes = window.ShowDialog();

            if (dlgRes == null)
                return;

            if (!dlgRes.Value)
                return;

            var pageService = new PageService();

            pageService.InitService();

            var keysToDelete = article.Words.Keys.Where(pageService.IsToDelete).ToList();

            foreach (var key in keysToDelete)
                article.Words.Remove(key);

            DbSingleton.DbProxy.AddArticleDb(article);
        }

        public static void AddInternetToDb(WordStatArticle wordStatArticle)
        {
            wordStatArticle.Words = WordParser.GetWords(wordStatArticle.Text);

            var pageService = new PageService();

            pageService.InitService();

            var keysToDelete = wordStatArticle.Words.Keys.Where(pageService.IsToDelete).ToList();

            foreach (var key in keysToDelete)
                wordStatArticle.Words.Remove(key);

            IDbProxy efDbProxy = new EfDbLayer.EfDbProxy();

            efDbProxy.AddArticleDb(wordStatArticle);
        }

        private static string GetText(string fileName)
        {
            try
            {
                return File.ReadAllText(fileName, Encoding.Default);
            }
            catch (SecurityException e)
            {
                MessageBox.Show("Can not read file. You have no permission for this file");
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBox.Show("Can not read file. You have no permission for this file");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return null;
        }
    }
}